<?php
namespace hangpu8\hpcms\service;
class CrudValidate
{
    /**
     * 创建规则数据
     *
     * @param array $validate
     * @return string
     */
    public function createRule(array $validate) : string
    {
        $str = '';
        foreach ($validate as $value)
        {
            $str .= "'{$value['field']}' => '";
            foreach ($value['rule'] as $value2)
            {
                $str .= "{$value2}|";
            }
            $str = substr($str,0,strlen($str)-1);
            $str .= "',\n";
        }
        $str = substr($str,0,strlen($str)-1);
        return $str;
    }

    /**
     * 创建错误消息数据
     *
     * @param array $validate
     * @return string
     */
    public function createMessage(array $validate) : string
    {
        $str = '';
        foreach ($validate as $value)
        {
            foreach ($value['rule'] as $key2=>$value2)
            {
                $str .= "'{$value['field']}.{$value2}' => ['code' => '{$value['code'][$key2]}', 'msg' => '{$value['message'][$key2]}'],\n";
            }
        }
        $str = substr($str,0,strlen($str)-1);
        return $str;
    }

    /**
     * 解析完整规则数据
     *
     * @param array $validate
     * @return array
     */
    public function parseRule(array $validate) :array
    {
        $rule = [];
        foreach ($validate as $key => $item)
        {
            $rule[$item['field']]['field'] = $item['field'];
            $rule[$item['field']]['rule'][$key] = $item['ruleName'];
            $code = empty($item['code']) ? 404 : $item['code'];
            $message = empty($item['message']) ? "请输入{$item['ruleTitle']}" : $item['message'];
            $rule[$item['field']]['code'][$key] = $code;
            $rule[$item['field']]['message'][$key] = $message;
        }
        return $rule;
    }
}